use strict;
use LWP::UserAgent;
use Crypt::SSLeay;
use JSON;
use HTTP::Cookies;
use HTTP::Status;
use Data::Dumper;
my $browser = LWP::UserAgent->new;
$browser->protocols_allowed( [ 'http', 'https'] );
my $cookieFile = "addama_lwp_cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
    file => $cookieFile,
  );
$cookie_jar->load($cookieFile);
$browser->cookie_jar($cookie_jar);
$browser->timeout(100);
$browser->env_proxy;
if ($#ARGV+1 != 4){
   die "You need to pass in directoryPath, fileType ([all = all files(includes sub directories)][ *.gif,*.png = only gif and png]], hostName and uri\n, I.E.: POST_Files.pl /local/myDirectory *.gif http://server:8080 /addama-rest/sept_repo/path/uploadFolder"
}
my ($fileDir, $fileType, $host, $uri) = @ARGV;
if ($fileType eq "all"){
   $fileType = "*";
}
my $urlFull = $host . $uri;
my $json = new JSON;
my $obj;
processUpload($fileDir, $uri);
checkResults();

sub processUpload {
  my $workDir = $_[0];
  my $workUri = $_[1];
  my $urlFull = $host . $workUri;
  printf "Source File Directory:$workDir fileTypes:$fileType url:$urlFull\n";
  #process directory -d 
my @fileNames = <$workDir/{$fileType}>;
  foreach (@fileNames) {
     if (-f $_){ 
        #print "File being uploaded: $_\n";
        uploadFile($_, $urlFull);
     }else{
       #print "Process subDirectory: $_\n"; 
       processDir($_,$workDir);
     }
  }
}
sub checkResults{
my $get_request = $browser->get($urlFull . '/dir');
  my $get_response = $get_request->content;
          # eval in case response isn't legit json
          eval { $obj = $json->decode($get_response) };
          if ($@) {
            print "Finish Uploading: $_\n";
          } else {
            print Dumper $obj;
          }

}

sub processDir{
   print "Directory name to create:$_[0]\n";
   #my @dirStruc = split('/', $_[0]);
   my $parentDir = $_[1];
   my @dirStruc = split($parentDir, $_[0]);
   my $dirNode = $dirStruc[-1]; 
   my $newDirPath = $urlFull . $dirNode . '/create';
   my $response = $browser->post($newDirPath);
   
   my $newWorkUri = $uri . $dirNode;
   if ($response->is_success) {
      print "Created new path $newDirPath \n";
      processUpload($_[0], $newWorkUri);	
   }else{
      print "Failed creating new path $newDirPath \n";
   }

} 

sub uploadFile{
   my $workUrl = $_[1];
   my $my_response = $browser->post($workUrl, Content_Type => 'form-data', Content => [filename => [$_[0]]]);
   if ($my_response->is_success) {
          print "Upload successful: $_\n";
      }
      else {
          print "Failed uploading: $_ with status $my_response->status_line\n";
          if($my_response->code()==401) {
            print "\nLogin is required, please run AddamaLogin.pl and try again.\n\n"
      }
    }
}
